wpf 按钮测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace wpfTest
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
private void MyRoutedEventHandler(object sender, RoutedEventArgs e)
{
lb.Items.Add(string.Format("时间:{0:hh:mm:ss}\t 发送者:{1:}\t 事件:{2}", DateTime.Now, ((FrameworkElement)sender).GetType().Name, e.RoutedEvent.Name));
}
public Window1()
{
InitializeComponent();
lb.Items.Clear();
//http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.mousedown.aspx
//A few ContentElement derived classes that have control-like behavior, for example, Hyperlink, might have inherent class handling for mouse button events. The left mouse button down event is the most likely event to have class handling in a control. The class handling often marks the underlying Mouse class event as handled. Once the event is marked handled, other instance handlers that are attached to that element are not ordinarily raised. Any other class or instance handlers that are attached to elements in the bubbling direction towards the root in the UI tree are also not ordinarily raised.
//由于某些控件内部有一些内建的事件处理,其MouseDown事件(包括MouseUp等)在处理完成之后将Handled标志置为true,附加事件PreviewMouseDown事件也就不再被执行,所以普通的MouseDown事件代码是不会有作用的。如果要使用MouseDown事件,要么使用PreviewMouseDown事件来替代,要么使用AddHandler来添加自定义的路由事件处理。
//为控件添加MouseDown事件处理,第3个参数必须为true,否则不起作用。
//TextBlock不需要添加
CancelButton.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(MyRoutedEventHandler), true);
sp.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(MyRoutedEventHandler), true);
grid.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(MyRoutedEventHandler), true);
myWindow.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(MyRoutedEventHandler), true);
}
}
}
评论